package a.codetop;

import org.junit.Test;

import java.util.Stack;

public class _15括号是否有效_简单栈 {
    @Test
    public void test() {
        System.out.println(isValid("()"));
    }

    public boolean isValid(String s) {

        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < chars.length; i++) {
            if(chars[i]=='{' || chars[i]=='(' || chars[i]=='[') stack.push(chars[i]);
            else{
                //没有可用的左括号
                if(stack.isEmpty())return false;

                if(chars[i]=='}'){
                    Character pop = stack.pop();
                    if(pop!='{')return false;
                }
                else if(chars[i]==')'){
                    Character pop = stack.pop();
                    if(pop!='(')return false;
                }
                else if(chars[i]==']'){
                    Character pop = stack.pop();
                    if(pop!='[')return false;
                }
            }
        }

        //栈里还剩 ((
        if(!stack.isEmpty())return false;
        return true;
    }

}
